package Web;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author wuhan
 * @date 2019/10/20 16:36
 */

class PicThread implements Runnable{
    private Socket s;

    public PicThread(Socket s) {
        this.s = s;
    }

    @Override
    public void run() {
        int count = 1;
        String hostAddress = s.getInetAddress().getHostAddress();
        try{

            System.out.println(hostAddress+"....connected");
            InputStream in = s.getInputStream();
            File file = new File(hostAddress+"("+(count)+")"+".jpg");
            while (file.exists()){
                file = new File(hostAddress+"("+(count++)+")"+".jpg");
            }
            FileOutputStream fos = new FileOutputStream(file);
            byte[] buf = new byte[1024];
            int len = 0;
            while ((len=in.read(buf))!=-1){
                fos.write(buf,0,len);
            }
            OutputStream out = s.getOutputStream();
            out.write("上传成功".getBytes());
            fos.close();
            s.close();
        }catch (Exception e){
            throw new RuntimeException(hostAddress+"上传失败");
        }
    }
}
public class MultiThreadServer {
    public static void main(String[] args) throws IOException {
        ServerSocket ss = new ServerSocket(10007);
        while (true){
            Socket s = ss.accept();
            new Thread(new PicThread(s)).start();
        }

    }
}
